package com.sl.core.engine.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.unit.DataSize;
import cn.hutool.core.io.unit.DataSizeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public final class ZipUtil {

    /**
     * 用于标识pangu压缩
     */
    private static final String PREFIX = "SQ_ZIP:";


    private ZipUtil(){}

    public static String zip(String content){

        if (CharSequenceUtil.isBlank(content)) {
            return content;
        }
        long sourceFileSize = DataSize.ofBytes(StrUtil.bytes(content).length).toBytes();
        Long startTime = System.currentTimeMillis();
        String res = doZip(content);
        Long endTime = System.currentTimeMillis();
        if (log.isDebugEnabled()) {
            long zipFileSize = DataSize.ofBytes(CharSequenceUtil.bytes(res).length).toBytes();
            log.debug("源文件大小 {} 压缩后文件大小{} 耗时{}ms", DataSizeUtil.format(sourceFileSize), DataSizeUtil.format(zipFileSize), endTime - startTime);
        }
        return res;
    }

    private static String doZip(String content) {
        byte[] gzip = cn.hutool.core.util.ZipUtil.gzip(content, CharsetUtil.defaultCharset().toString());
        String encode = Base64.encode(gzip);
        return CharSequenceUtil.prependIfMissing(encode,PREFIX,PREFIX);
    }



    public static String unZip(String content) {
        if (CharSequenceUtil.isBlank(content)) {
            return content;
        }
        if (!content.contains(PREFIX)) {
            return content;
        }
        long sourceFileSize = DataSize.ofBytes(CharSequenceUtil.bytes(content).length).toBytes();
        Long startTime = System.currentTimeMillis();
        byte[] decode = Base64.decode(CharSequenceUtil.removePrefix(content, PREFIX));
        String gzip = cn.hutool.core.util.ZipUtil.unGzip(decode, CharsetUtil.defaultCharset().toString());
        Long endTime = System.currentTimeMillis();
        if (log.isDebugEnabled()) {
            long zipFileSize = DataSize.ofBytes(CharSequenceUtil.bytes(gzip).length).toBytes();
            log.debug("源文件大小 {} 解压缩后文件大小{} 耗时{}ms", DataSizeUtil.format(sourceFileSize), DataSizeUtil.format(zipFileSize), endTime - startTime);
        }
        return gzip;
    }
}
